<template>
    <Layout>
        <Form ref="form1" :model="form1" :label-width="120">
            <Row v-show="!switchFlag" class="query-form">
                <Col span="8">
                    <FormItem label="企业名称：">
                        <Input class="query-form-el" type="text" v-model="form1.stdOrgName"></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="自评计划名称：" prop="planName">
                        <Input class="query-form-el" type="text" v-model="form1.planName"></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开
                        <Icon type="ios-arrow-down"/>
                    </Button>
                    <Button @click="reset" class="ivu-btn-reset">重置</Button>
                    <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
                </Col>
            </Row>
            <Row v-show="switchFlag" class="query-form">
                <Col span="8">
                    <FormItem label="企业名称：" prop="stdOrgName">
                        <Input class="query-form-el" type="text" v-model="form1.stdOrgName"></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="自评计划名称：" prop="planName">
                        <Input class="query-form-el" type="text" v-model="form1.planName"></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="计划自评时间：" prop="planDate">
                        <DatePicker type="daterange"  v-model="planDate" split-panels placeholder="请选择" style="width: 100%"></DatePicker>
                    </FormItem>
                </Col>
            </Row>
            <Row v-show="switchFlag" class="query-form">
                <Col span="8">
                    <FormItem label="录入人:">
                        <Input class="query-form-el" type="text" v-model="form1.editor"></Input>
                    </FormItem>
                </Col>
                <Col span="16">
                    <Div style="float: right;">
                        <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起
                            <Icon type="ios-arrow-up"/>
                        </Button>
                        <Button @click="reset" class="ivu-btn-reset">重置</Button>
                        <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
                    </Div>
                </Col>
            </Row>
            <Row class="query-form">
                <Col span="24">
                    <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo">新增</Button>
                </Col>
            </Row>
        </Form>

        <Table ref='table' :height="tableHeight" size="small" :loading="loading" no-data-text="没有查询到相关数据!"
               @on-selection-change='getSelectRows'
               border :columns="columns1" :data="dataTable">
        </Table>
        <Row style="margin-right:10px;">
            <Col span="24">
                <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize"
                      @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray"
                      show-total show-sizer show-elevator/>
            </Col>
        </Row>
        <Modal :title="add?'标准化自评计划新增':'标准化自评计划修改'" :mask-closable="false" v-if="form1datacopy && model1" :transfer=false v-model="model1" :width=600>
            <Row>
                <Col span="24">
                    <Form ref="form1datacopy" :model="form1datacopy" :rules="ruleCustom" label-position="top">
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem label="企业名称：" prop="stdOrgId">
                                    <cascaderDom class="query-form-el" style="padding-top: 4px" ref="trainOrg"
                                                 @setOrgInfo="setOrgId" @setOrgname="setOrgName"
                                                 :currentOrgId="stdOrgId"
                                                 :currentOrgName="stdOrgName" :orgTree="true"></cascaderDom>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label="自评计划名称：" prop="planName">
                                    <Input type="text" class="query-form-el" v-model="form1datacopy.planName"/>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label="计划自评时间：" prop="planDate">
                                    <DatePicker type="date" placeholder="请选择" class="query-form-el"
                                                v-model="form1datacopy.planDate"></DatePicker>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label="录入人：" prop="editor">
                                    <Input type="text" class="query-form-el" v-model="form1datacopy.editor"/>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label="电话:" prop="phone">
                                    <Input type="text" class="query-form-el" v-model="form1datacopy.phone"/>
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                </Col>
            </Row>
            <div slot="footer">
                <Button :disabled="saveMod" class='ivu-btn-save' :loading="buttonLoading"
                        @click="submit('form1datacopy')">确定
                </Button>
                <Button class='ivu-btn-cancel' @click="handleCancel">取消</Button>
            </div>
        </Modal>
        <Modal title="安全标准化计划详情" :transfer=false v-model="model2" :width=800 class="modal-view-detail">
            <Row>
                <Col span="24">
                    <Form :model="form1datacopy" :label-width="160">
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label="企业名称：" prop="stdOrgName">
                                    {{form1datacopy.stdOrgName}}
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label="自评计划名称：" prop="planName">
                                    {{form1datacopy.planName}}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label="计划自评时间：" prop="planDate">
                                    {{formatDate(new Date(form1datacopy.planDate), 'yyyy-MM-dd')}}
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label="录入人：" prop="editor">
                                    {{form1datacopy.editor}}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">

                            <Col span="11">
                                <FormItem label="电话:" prop="phone">
                                    {{form1datacopy.phone}}
                                </FormItem>
                            </Col>
                            <Col span="11">
                            </Col>
                        </Row>
                    </Form>
                </Col>
            </Row>
            <div slot="footer">
                <Button class='ivu-btn-save' @click="model2=false">关闭</Button>
            </div>
        </Modal>

    </Layout>
</template>

<script>
    import {Api} from '../../../api'
    import {sessionStorage} from '../../../common/cacheUtils.js';
    import {mapState, mapGetters, mapActions} from 'vuex'
    import pageCommonFunction from '@/components/pageCommonFunction.js'
    import cascaderDom from '../../../components/cascader-dom.vue';

    export default {
        components: {
            cascaderDom
        },
        data() {
            return {
                ...this.createCommonDataField(),
                companyId: sessionStorage('userId').getObject('userId').companyId,
                downloadUrl: Api.downloadMongoFile,
                upUrl: Api.uploadMongoFile,
                switchFlag: false,
                saveMod: false,
                planDate:['',''],
                form1: {},
                uploadList: [],
                pageSizeArray: [10, 20, 50],
                pagedata: {
                    total: 0,
                    pageSize: 10,
                    currentPage: 1,
                },
                dataTable: [],
                columns1: [
                    {
                        title: "序号",
                        width: 80,
                        align: "center",
                        fixed: 'left',
                        render: (h, params) => {
                            return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
                        }
                    },
                    {
                        title: '企业名称',
                        fixed: 'left',
                        minWidth: 300,
                        align: 'center',
                        key: 'stdOrgName',
                    },
                    {
                        title: '自评计划名称',
                        fixed: 'left',
                        minWidth: 130,
                        align: 'center',
                        key: 'planName'
                    },
                    {
                        title: '计划自评时间',
                        minWidth: 280,
                        align: 'center',
                        key: 'lastEvaluateTime',
                        render: (h, params) => {
                            return h('div', [
                                (this.formatDate(new Date(params.row.planDate), 'yyyy-MM-dd'))
                            ]);
                        }
                    },
                    {
                        title: '录入人',
                        minWidth: 150,
                        align: 'center',
                        key: 'editor'
                    },
                    {
                        title: '电话',
                        minWidth: 150,
                        align: 'center',
                        key: 'phone'
                    },
                    {
                        title: '操作',
                        key: 'action',
                        fixed: 'right',
                        width: 200,
                        align: 'center',
                        render: (h, params) => {
                            if (this.currentUser.loginId === this.Common.admin || this.currentUser.userId === params.row.createUsrId || this.currentUser.userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined
                                ||sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined) {
                                return h('div', [
                                    h('A', {
                                        props: {
                                            type: 'primary',
                                            size: 'small'
                                        },
                                        style: {
                                            fontSize: '14px',
                                        },
                                        on: {
                                            click: () => {
                                                this.showData(params, 1);
                                            }
                                        }
                                    }, '详情'),
                                    h('Divider', {
                                        props: {
                                            type: 'vertical',
                                        }
                                    }, ''),
                                    h('A', {
                                        props: {
                                            type: 'primary',
                                            size: 'small'
                                        },
                                        style: {
                                            fontSize: '14px',

                                        },
                                        on: {
                                            click: () => {
                                                this.showData(params, 2);
                                            }
                                        }
                                    }, '修改'),
                                    h('Divider', {
                                        props: {
                                            type: 'vertical',
                                        }
                                    }, ''),
                                    h('A', {
                                        props: {
                                            type: 'primary',
                                            size: 'small'
                                        },
                                        style: {
                                            fontSize: '14px',
                                            color: 'red'
                                        },
                                        on: {
                                            click: () => {
                                                this.$Modal.confirm({
                                                    title: '提示',
                                                    content: '<p>是否要删除？</p>',
                                                    onOk: () => {
                                                        this.deleteData(params);
                                                    },
                                                    onCancel: () => {
                                                    }
                                                });
                                            }
                                        }
                                    }, '删除')
                                ]);
                            } else {
                                return h('div', [
                                    h('A', {
                                        props: {type: 'primary', size: 'small'},
                                        style: {fontSize: '14px',},
                                        on: {
                                            click: () => {
                                                this.showData(params, 1);
                                            }
                                        }
                                    }, '详情'),
                                    h('Divider', {props: {type: 'vertical'}}, ''),
                                    h('A', {
                                        props: {type: 'primary', size: 'small'},
                                        style: {fontSize: '14px', color: '#c5c8ce'}
                                    }, '修改'),
                                    h('Divider', {props: {type: 'vertical'}}, ''),
                                    h('A', {
                                        props: {type: 'primary', size: 'small'},
                                        style: {fontSize: '14px', color: '#c5c8ce'}
                                    }, '删除')
                                ]);
                            }

                        }
                    },

                ],
                ruleCustom: {
                    stdOrgId: [
                        {required: true, message: '  ', trigger: 'change'}
                    ],
                    planName: [
                        {required: true, message: '  ', trigger: 'change'}
                    ],
                    editor: [
                        {required: true, message: '  ', trigger: 'change'}
                    ],
                    phone: [
                        {validator: (rule, value, callback) => {
                                if (!(/^1[3456789]\d{9}$/.test(value))) {
                                    callback(' ');
                                } else {
                                    callback()
                                }
                            },
                            required: true, message: '  ', trigger: 'change'}
                    ],
                    planDate: [{
                        validator: (rule, value, callback) => {
                            if (value == null || value == '' || value == undefined) {
                                callback(' ')
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'change'
                    }]
                },
                stdOrgName: '',
                stdOrgId: '',
                add: false,
                model1: false,
                buttonLoading: false,
                model2: false,
                showdata: {},
                exportUrl: Api.exportSaStdStandard,
                location: null,
                form1datacopy: {},
                files: [],
                tableHeight: 10,
                loading: false,
                twoLevelOrgList: []
            }
        },
        async mounted() {
            this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
            let orgId = sessionStorage('userId').getObject('userId');
            this.query();
        },
        methods: {
            ...pageCommonFunction,
            setOrgId(data) {
                this.form1datacopy.stdOrgId = data[data.length - 1];
            },
            setOrgName(data) {
                this.form1datacopy.stdOrgName = data;
            },
            deleteData(params) {
                let url = Api.deleteSaStdStandardPlan;
                this.$http.delete(url + '/' + params.row.standardPlanId, {params: {}}).then((res) => {
                    if (res.data.status === 200) {
                        this.$Message.success('成功');
                        this.query()
                    } else if (res.data.status === 201) {
                        this.$Message.error(res.data.msg);

                    }
                }).catch(e => {
                    this.$Message.error('请求失败' + e);
                })
            },


            getSelectRows(rows) {
                this.deleteRows = rows;
            },
            batDelete() {

            },
            get_uuid() {
                let s = [];
                let hexDigits = "0123456789abcdef";
                for (let i = 0; i < 36; i++) {
                    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
                }
                s[14] = "4";
                s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
                s[8] = s[13] = s[18] = s[23] = "-";

                let uuid = s.join("");
                let reg = new RegExp("-", "g");
                let a = uuid.replace(reg, "");
                console.log(a);
                return a;
            },
            setOrgId1(data) {
                this.form1.orgId = data[data.length - 1];
            },
            setOrgName1(data) {
                this.form1.orgName = data;
            },
            addInfo() {
                this.uploadList = []
                this.saveMod = false;
                this.form1datacopy = {
                    standardPlanId: this.get_uuid()
                };
                this.stdOrgName = '';
                this.stdOrgId = '';
                this.files = [];
                this.model1 = true;
                this.add = true;
            },
            pageChange(pageNum) {
                this.pagedata.currentPage = pageNum;
                this.query();
            },
            pageSizeChange(pageSize) {
                this.pagedata.pageSize = pageSize;
                this.query();
            },
            handleCancel() {
                this.form1datacopy = {};
                this.model1 = false;
            },
            switchQuery(flag) {
                this.switchFlag = flag;
                if (!this.switchFlag) {
                    this.tableHeight = this.tableHeight + 76;
                } else {
                    this.tableHeight = this.tableHeight - 76;
                }
            },
            reset() {
                this.form1 = {};
                this.appDate = ["", ""];
                this.query();

            },
            exportExcel() {
                this.form1.orgId = sessionStorage('userId').getObject('userId').companyId
                if (this.appDate[0] != "" && this.appDate[1] != "") {
                    this.form1.startDate = this.formatDate(new Date(this.appDate[0]), 'yyyy-MM-dd');
                    this.form1.endDate = this.formatDate(new Date(this.appDate[1]), 'yyyy-MM-dd');
                }
                this.dataToQuery = this.form1
                this.exportFormSubmit()
            },
            query() {
                this.loading = true;
                let data = {
                    startPage: this.pagedata.currentPage,
                    size: this.pagedata.pageSize,
                    orgId: sessionStorage('userId').getObject('userId').companyId

                };
                if (this.planDate[0] != "" && this.planDate[1] != "") {
                    this.form1.startDate = this.formatDate(new Date(this.planDate[0]), 'yyyy-MM-dd');
                    this.form1.endDate = this.formatDate(new Date(this.planDate[1]), 'yyyy-MM-dd');
                }
                data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));

                let url = Api.querySaStdStandardPlan;
                this.$http.get(url, {params: data}).then((res) => {
                    this.dataTable = res.data.data.data;
                    this.pagedata.total = res.data.data.totalSize;
                    this.loading = false;
                }).catch(e => {
                    this.$Message.error("数据获取失败")
                })
            },
            showData(data, flag) {
                this.stdOrgId = data.row.stdOrgId;
                this.stdOrgName = data.row.stdOrgName;
                if (flag == 1) {
                    //查看页面
                    this.form1datacopy = data.row;
                    this.form1datacopy.planDate = this.formatDate(new Date(this.form1datacopy.planDate), 'yyyy-MM-dd');
                    this.model2 = true;
                } else {
                    this.saveMod = false;
                   //修改页面
                    this.add = false;
                    console.log(data.row);
                    this.form1datacopy = data.row;
//                    this.form1datacopy.planDate = this.formatDate(new Date(this.form1datacopy.planDate), 'yyyy-MM-dd');
                    this.model1 = true;
                }
            },
            submit(name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        this.buttonLoading = true
                        this.saveMod = true;
                        this.form1datacopy.planDate = this.formatDate(new Date(this.form1datacopy.planDate), 'yyyy-MM-dd');
                        if (this.add) {
                            let userId = sessionStorage('userId').getObject('userId').userId;
                            let orgId = sessionStorage('userId').getObject('userId').orgInfo.orgId;
                            this.form1datacopy.createUsrId = userId;
                            this.form1datacopy.createOrgId = orgId;
                            this.form1datacopy.updateUserId = userId;
                            this.form1datacopy.updateOrgId = orgId;
                            this.$http.post(Api.saveSaStdStandardPlan, this.form1datacopy).then((res) => {
                                if (res.data.status === 200) {
                                    this.$Message.success('成功');
                                    this.model1 = false;
                                    this.saveMod = false;
                                    this.query()
                                } else if (res.data.status === 201) {
                                    this.$Message.error(res.data.msg);
                                    this.model1 = false;
                                }
                                this.buttonLoading = false
                            }).catch(e => {
                                this.model1 = false;
                                this.query();
                                this.buttonLoading = false
                                this.$Message.error("数据获取失败")
                            })
                        } else {
                            let userId = sessionStorage('userId').getObject('userId').userId;
                            let orgId = sessionStorage('userId').getObject('userId').orgInfo.orgId;
                            this.form1datacopy.updateUserId = userId;
                            this.form1datacopy.updateOrgId = orgId;
                            this.$http.post(Api.updateSaStdStandardPlan, this.form1datacopy).then((res) => {
                                if (res.data.status === 200) {
                                    this.$Message.success('成功');
                                    this.saveMod = false;
                                    this.model1 = false;
                                    this.query()

                                } else if (res.data.status === 201) {
                                    this.$Message.error(res.data.msg);
                                    this.model1 = false;
                                }
                                this.buttonLoading = false
                            }).catch(e => {
                                this.model1 = false;
                                this.query();
                                this.buttonLoading = false
                                this.$Message.error("数据获取失败")
                            })
                        }
                    } else {
                        this.$Message.error('请填报完整!');
                    }
                })
            },
            formatDate(date, fmt) {
                if (/(y+)/.test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
                }
                let o = {
                    'M+': date.getMonth() + 1,
                    'd+': date.getDate(),
                    'h+': date.getHours(),
                    'm+': date.getMinutes(),
                    's+': date.getSeconds()
                };
                for (let k in o) {
                    if (new RegExp(`(${k})`).test(fmt)) {
                        let str = o[k] + '';
                        fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
                    }
                }
                return fmt;
            },
            padLeftZero(str) {
                return ('00' + str).substr(str.length);
            },

        },
        watch: {
            "model1": function (qw, er) {
                if (qw && this.model1) {
                    setTimeout(() => {
                        this.$refs.trainOrg.setCurrentOrg();
                    }, 100)
                } else {
                    this.$refs.trainOrg.setCurrentOrg();

                }
            },

        },


    }
</script>

<style lang='css' scoped>
    @import '../../../index.css';
</style>
